package com.zhisuo.apicenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhisuo.apicenter.Constants;
import com.zhisuo.apicenter.aes.GetPhoneNumber;
import com.zhisuo.apicenter.model.*;
import com.zhisuo.apicenter.service.ApiService;
import com.zhisuo.apicenter.service.UserManService;
import com.zhisuo.apicenter.util.DateUtil;
import com.zhisuo.apicenter.util.SendSmsUtil;
import com.zhisuo.apicenter.util.StringUtil;
import com.zhisuo.apicenter.util.WxCommonUtil;
import com.zhisuo.apicenter.wxpayutil.HttpUtils;
import com.zhisuo.apicenter.wxpayutil.PayUtil;
import com.zhisuo.apicenter.wxpayutil.XmlUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/api")
public class ApiController {

    private static final Logger log = LoggerFactory.getLogger(ApiController.class);

    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }

    private UserManService userManService;
    @Autowired
    public void setUserManService(UserManService userManService) {
        this.userManService = userManService;
    }


    /**
     * 处理超时订单
     */
    @RequestMapping(value = "/getNoDeliveryOrderByStop")
    public void getNoDeliveryOrderByStop(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getNoDeliveryOrderByStop-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);

        String beforestop = jsonObject.getString("beforestop");
        String carid = jsonObject.getString("carid");
        ZhiSuoCar car = userManService.getZhiSuoCarByCarId(carid);
        if (StringUtil.isNotEmpty(beforestop)) {

            //设置超时未取发送短信
            List<DeliveryOrder> listNoDeliveryOrder = userManService.getListNoDeliveryOrderBySync(car.getId() + "", beforestop);
            //System.out.println("listNoDeliveryOrder-----"+listNoDeliveryOrder.size());
            if (listNoDeliveryOrder != null && listNoDeliveryOrder.size() > 0) {

                for (DeliveryOrder order : listNoDeliveryOrder) {

                    //短信通知重新预约，订单状态变更为待预约
                    //【智梭无人车】亲爱的小主,您的快件没有在预约时间内领取，请打开微信小程序，搜索智梭无人车，重新预约哟~

                    userManService.insertNewZhiSuoCarNextStopSms("", order.getReceiptusermobile(), order.getCarid() + "", 3);

                    //将订单状态改变

                    if(order.getOrdertype()==1){
                        //只有零售端才下发商家短信
                        String sellermobile=userManService.getMobilByUserId(order.getUserid()+"");
                        userManService.insertNewZhiSuoCarNextStopSms(order.getCreate_time()+","+order.getReceiptusermobile(),sellermobile , order.getCarid() + "", 4);
                        userManService.updateSellerOrderStatusAgainOrderByOrderId(order.getId());
                    }else{
                        userManService.updateOrderStatusAgainOrderByOrderId(order.getId());
                    }


                }
            }


        }

        JSONObject resultData = new JSONObject();
        resultData.put("error_code", 0);
        resultData.put("error_msg", "操作成功");
        responseData(resultData.toString(), resp);
    }



    /**
     *  获取首页轮播图
     */
    @RequestMapping(value = "/getSysIndexImgByStatus")
    public void getSysIndexImgByStatus(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getSysIndexImgByStatus-----------------------:" + str);
        List<String> listimg=apiService.getListSysIndexImgByStatus();
        JSONArray imagearray=new JSONArray();
        if(listimg != null&& listimg.size()>0){
            JSONObject imagejson=null;
            for(String img:listimg){
                imagejson=new JSONObject();
                imagejson.put("imageurl",img);
                imagearray.add(imagejson);
            }
        }
        JSONObject resultData = new JSONObject();
        resultData.put("error_code", 0);
        resultData.put("error_msg", "获取成功");
        resultData.put("data", imagearray);
        responseData(resultData.toString(), resp);
    }

    /**
     * 根据手机号获取用户默认地址
     */
    @RequestMapping(value = "/getDefaultAddressByPhone")
    public void getDefaultAddressByPhone(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getDefaultAddressByPhone-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);

        String mobile = jsonObject.getString("mobile");
        String parkareaid=jsonObject.getString("parkareaid");
        ZhiSuoUser user=userManService.getZhiSuoUserByMobile(mobile);

        //获取用户默认地址
        ZhiSuoUserAddress userAddress=userManService.getZhisuoFlagUserAddressByUserId(user.getId());
        ParkAreaBuild buildinfo=userManService.getParkAreaBuildById(userAddress.getParkareabuildid());
        JSONObject addressjson=new JSONObject();
        if(parkareaid.equals(buildinfo.getParkareaid()+"")){
            ParkArea area=userManService.getParkAreaById(buildinfo.getParkareaid());
            addressjson.put("areaname",area.getName());
            addressjson.put("areaid",area.getId());
            addressjson.put("buildid",buildinfo.getId());
            addressjson.put("buildname",buildinfo.getName());
        }else if(parkareaid.equals("-1")){
            ParkArea area=userManService.getParkAreaById(buildinfo.getParkareaid());
            addressjson.put("areaname",area.getName());
            addressjson.put("areaid",area.getId());
            addressjson.put("buildid",buildinfo.getId());
            addressjson.put("buildname",buildinfo.getName());
        }

        JSONObject resultData = new JSONObject();
        resultData.put("error_code", 0);
        resultData.put("error_msg", "获取成功");
        resultData.put("data", addressjson);
        responseData(resultData.toString(), resp);
    }



    /**
     * 根据部分手机号匹配用户手机
     */
    @RequestMapping(value = "/getListPhoneByNumber")
    public void getListPhoneByNumber(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getListPhoneByNumber-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String phonenumber = jsonObject.getString("phonenumber");
        List<String> liststring=apiService.getListPhoneByPhoneNumber(phonenumber);
        JSONObject resultData = new JSONObject();
        resultData.put("error_code", 0);
        resultData.put("error_msg", "电话列表");
        resultData.put("data", liststring);
        responseData(resultData.toString(), resp);
    }



    /**
     * 用户我的数据
     */
    @RequestMapping(value = "/getMainInfoByUserId")
    public void getMainInfoByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getMainInfoByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);

        String userid = jsonObject.getString("userid");
        JSONObject datajson=new JSONObject();
        String daydate= DateUtil.getDate();
        String usersignid=apiService.getZhiSuoUserSignRecordByUserDate(userid,daydate);

        //判断是否已经签到
        if(StringUtils.isNotEmpty(usersignid)){
            datajson.put("issgin", 1);
        }else{
            datajson.put("issgin",0);
        }
        Integer sign_integral=apiService.getAwardIntegeralByConfig("sign_integral");
        //签到获取积分
        datajson.put("sign_integral",sign_integral);
        JSONObject resultData = new JSONObject();
        resultData.put("error_code", 0);
        resultData.put("error_msg", "签到列表");
        resultData.put("data", datajson);
        responseData(resultData.toString(), resp);
    }


    /**
     * 用户获取积分记录
     */
    @RequestMapping(value = "/getListUseSignRecordByUserId")
    public void getListUseSignRecordByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getListUseSignRecordByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        Integer page = jsonObject.getInteger("page");
        ZhiSuoUser user=apiService.getUserInfoByUserId(userid);
        JSONObject datajson=new JSONObject();
        datajson.put("integral",user.getIntegral());
        // 0待派件  3已签收   4派送中
        List<ZhiSuoUserIntegralRecord> listZhiSuoUserIntegralRecord = apiService.getListZhiSuoUserIntegralRecordByUserId(userid, page, Constants.PAGESIZE);
        datajson.put("listZhiSuoUserIntegralRecord",listZhiSuoUserIntegralRecord);
        JSONObject resultData = new JSONObject();
        resultData.put("error_code", 0);
        resultData.put("error_msg", "积分记录列表");
        resultData.put("data", datajson);
        responseData(resultData.toString(), resp);
    }



    /**
     * 用户签到奖励积分
     */
    @RequestMapping(value = "/submitUseSignByIntegral")
    public void submitUseSignByIntegral(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("submitUseSignByIntegral-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);

        String userid = jsonObject.getString("userid");
        String daydate= DateUtil.getDate();

        String usersignid=apiService.getZhiSuoUserSignRecordByUserDate(userid,daydate);

        if(StringUtils.isNotEmpty(usersignid)){
            responseErrorData("用户当日已签完到", resp);
            return;
        }
        //加入用户积分
        Integer sign_integral=apiService.getAwardIntegeralByConfig("sign_integral");
        //用户增加积分
        userManService.updateUserIntegralByUserId(userid,sign_integral);
        //增加积分记录
        userManService.insertNewZhiSuoUserIntegralRecord(userid,0,sign_integral,0,2);
        //增加用户签到列表
        userManService.insertZhiSuoUserSignRecord(userid,daydate);

        JSONObject resultData = new JSONObject();
        resultData.put("error_code", 0);
        resultData.put("error_msg", "签到成功");
        responseData(resultData.toString(), resp);
    }


    /**
     * 用户提现
     */
    @RequestMapping(value = "/submitUserMoneyByIntegral")
    public void submitUserMoneyByIntegral(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("submitUserMoneyByIntegral-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");

        Map<String, String> restmap = null;

        try {
            String total_fee = BigDecimal.valueOf(0.01).multiply(BigDecimal.valueOf(100))
                    .setScale(0, BigDecimal.ROUND_HALF_UP).toString();
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("mch_appid", Constants.WXAPP_ID);
            parm.put("mch_id", Constants.WXPAYMCH_ID);
            parm.put("nonce_str", PayUtil.getNonceStr());
            parm.put("partner_trade_no", "tradeno");
            parm.put("openid", "openid");
            parm.put("check_name", "NO_CHECK");
            parm.put("amount", total_fee);
            parm.put("desc", "企业付款备注");
            parm.put("sign", PayUtil.getSign(parm, Constants.WXPAYAPI_SECRET));

            String restxml = HttpUtils.post(Constants.WXORDER_PAY, XmlUtil.xmlFormat(parm, true));
            restmap = XmlUtil.xmlParse(restxml);
            //System.out.println("restmap-------" + restmap.toString());
            LogFactory.getLog(this.getClass()).info("restmap--------" + restmap);
        } catch (Exception e) {

        }

        Map<String, String> payMap = new HashMap<String, String>();

        JSONObject resultData = new JSONObject();
        resultData.put("error_code", 0);
        resultData.put("error_msg", "提现成功");
        responseData(resultData.toString(), resp);



    }


    /**
     * 首次打开小程序，授权，上传OpenId并返回UserId
     * @param req
     * @param resp
     * @throws Exception 检查
     */
    @RequestMapping(value = "/getWxUnionidUserId")
    public void getWxUnionidUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        log.info("getWxUnionidUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        // 小程序APPID
        String appid = Constants.WXAPP_ID;
        // 小程序APPSECRET
        String secret = Constants.WXAPPSCERET;
        // JS_CODE
        String jscode = jsonObject.getString("js_code");
        String result = WxCommonUtil.getUNIONID(appid, secret, jscode);
        log.info("getWxUnionidUserId------------result-----------:" + result);
        String userid = "";
        int type = 0;
        JSONObject userjson = new JSONObject();
        if (StringUtils.isNotEmpty(result)) {
            JSONObject returnjsonObject = JSONObject.parseObject(result);
            String openid = returnjsonObject.getString("openid");
            if (StringUtil.isEmpty(openid)) {
                resultObj.put("error_code", 1);
                resultObj.put("error_msg", "openid为空");
                resultObj.put("data", "");
                responseData(resultObj.toString(), resp);
                return;
            }
            ZhiSuoUser user = apiService.getUserIdByOpenId(openid);

            if (user == null) {
                userid = apiService.insertNewUserByOpenId(openid);
                userjson.put("avatarurl", "");
                userjson.put("userid", userid);
                userjson.put("nickname", "");
                userjson.put("mobile", "");
                userjson.put("role", "");
                userjson.put("integral",0);

            } else {
                userid = user.getId() + "";

                userjson.put("avatarurl", user.getAvatarurl());
                userjson.put("userid", user.getId());
                userjson.put("nickname", user.getNickname());
                userjson.put("mobile", user.getMobile());
                userjson.put("role", user.getRole());
                userjson.put("integral",user.getIntegral());


            }
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "获取成功");
            resultObj.put("data", userjson);
            responseData(resultObj.toString(), resp);
        } else {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "系统异常,授权出错");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
        }

    }


    /**
     * 获取园区列表信息
     */
    @RequestMapping(value = "/getListParkArea")
    public void getListParkArea(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        JSONObject resultObj = new JSONObject();
        List<ParkArea> listParkArea = apiService.getListParkArea();

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        if (listParkArea != null && listParkArea.size() > 0) {
            for (ParkArea pa : listParkArea) {
                jsonObject = new JSONObject();
                jsonObject.put("parkareaid", pa.getId());
                jsonObject.put("name", pa.getName());
                jsonArray.add(jsonObject);
            }
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);
    }

    /**
     * 根据园区ID获取楼号列表
     */
    @RequestMapping(value = "/getListParkAreaBuildByParkAreaId")
    public void getListParkAreaBuildByParkAreaId(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        log.info("getListParkAreaBuildByParkAreaId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        //园区ID
        String parkareaid = jsonObject.getString("parkareaid");
        List<ParkAreaBuild> listParkArea = apiService.getListParkAreaBuildByParkAreaId(parkareaid);

        JSONArray jsonArray = new JSONArray();
        JSONObject jo = null;
        if (listParkArea != null && listParkArea.size() > 0) {
            for (ParkAreaBuild pa : listParkArea) {
                jo = new JSONObject();
                jo.put("parkareabuildid", pa.getId());
                jo.put("name", pa.getName());
                jsonArray.add(jo);
            }
        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", jsonArray);
        responseData(resultObj.toString(), resp);
    }

    /**
     * 获取手机验证码
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    @RequestMapping(value = "/getSecretByMobile")
    public void getMagazineList(HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        log.info("getSecretByMobile-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        // 小程序APPID
        String mobile = jsonObject.getString("mobile");
        // 判断手机号码正不正确,因前端判断,后端不判断
        String secret = RandomStringUtils.random(4, "1234567890");
        String[] params = new String[]{secret};
        String[] phoneNumbers = new String[]{mobile};
        String smsjson = SendSmsUtil.sendSmsPhoneCode(params, phoneNumbers);
        JSONObject json = JSONObject.parseObject(smsjson);
//		短信平台返回正确 则代表发送成功
        if (json.getString("result").equals("0")) {
            String id = apiService.getMobileSecret(mobile);
            if (StringUtil.isEmpty(id)) {
                apiService.insertMobileSecret(mobile, secret);
            } else {
                apiService.updateMObileSecret(mobile, secret, id);
            }
        } else {
            responseErrorData("发送失败", resp);
        }
//        String secret = "123456";
//        String id = apiService.getMobileSecret(mobile);
//        if (StringUtil.isEmpty(id)) {
//            apiService.insertMobileSecret(mobile, secret);
//        } else {
//            apiService.updateMObileSecret(mobile, secret, id);
//        }
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "发送成功");
        responseData(resultObj.toString(), resp);
    }


    /**
     * 注册-手机-验证码-地址
     */
    @RequestMapping(value = "/setRegisterMobileByUserId")
    public void setMobileByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setRegisterMobileByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String userid = jsonObject.getString("userid");
        String mobile = jsonObject.getString("mobile");
        String secret = jsonObject.getString("secret");
        String parkareabuildid = jsonObject.getString("parkareabuildid");

        if (StringUtils.isEmpty(parkareabuildid)) {
            responseErrorData("楼号不能为空", resp);
            return;
        }


        //第一步，判断验证码是否正确
        String usersecretid = apiService.getUserSecretIdByMobileAndSecret(mobile, secret);
        if (StringUtils.isNotEmpty(usersecretid)) {


            //查询地址是否存在库中
            String useraddressid = apiService.getUserAddressIdByUserIdAndPrkareabuildid(userid, parkareabuildid);

            if (StringUtils.isEmpty(useraddressid)) {
                apiService.insertNewUserAddrss(userid, parkareabuildid, "1");
            }

            //查询角色 0用户   1派件员  2零售员
            String salesmanid = apiService.getSalesManIdByMobile(mobile);

            String sellermanid = apiService.getSellerManIdByMobile(mobile);
            Integer role = 0;
            if (StringUtils.isNotEmpty(salesmanid)) {
                apiService.updateMobileByUserId(mobile, userid, 1, salesmanid);
                role = 1;
            } else if (StringUtils.isNotEmpty(sellermanid)) {
                apiService.updateMobileByUserId(mobile, userid, 2, sellermanid);
                role = 2;
            } else {
                apiService.updateMobileByUserId(mobile, userid, 0, "0");
            }

            //更新用户手机号，并查看地址是否有有增加，无则添加

            JSONObject jo = new JSONObject();
            jo.put("userid", userid);
            jo.put("role", role);
            jo.put("mobile", mobile);
            jo.put("integral", 0);
            resultObj.put("error_code", 0);
            resultObj.put("error_msg", "注册成功");
            resultObj.put("data", jo);
        } else {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "验证码错误");
            resultObj.put("data", "");
        }


        responseData(resultObj.toString(), resp);
    }


    /**
     * 登录  手机号，验证码
     */
    @RequestMapping(value = "/setLoginMobileByUserId")
    public void setLoginMobileByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setLoginMobileByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        String mobile = jsonObject.getString("mobile");
        String secret = jsonObject.getString("secret");


        //第一步，判断验证码是否正确
        String usersecretid = apiService.getUserSecretIdByMobileAndSecret(mobile, secret);
        if (StringUtils.isNotEmpty(usersecretid)) {
            ZhiSuoUser user = apiService.getUserRoleByMobile(mobile);

            if (user == null) {
                resultObj.put("error_code", 1);
                resultObj.put("error_msg", "用户不存在");
                resultObj.put("data", "");


            } else {
                JSONObject jo = new JSONObject();
                jo.put("userid", user.getId());
                jo.put("role", user.getRole());
                jo.put("mobile", user.getMobile());
                jo.put("avatarurl", user.getAvatarurl());
                jo.put("nickname", user.getNickname());
                jo.put("city", user.getCity());
                jo.put("province", user.getProvince());
                jo.put("country", user.getCountry());
                jo.put("gender", user.getGender());
                jo.put("integral", user.getIntegral());

                resultObj.put("error_code", 0);
                resultObj.put("error_msg", "登录成功");
                resultObj.put("data", jo);
            }

        } else {
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "验证码错误");
            resultObj.put("data", "");
        }
        responseData(resultObj.toString(), resp);
    }


    /**
     * 获取手机号码
     *
     * @param req
     * @param resp
     * @throws Exception 检查 一
     */
    @RequestMapping(value = "/getPhoneNumber")
    public void getPhoneNumber(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("getPhoneNumber------" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        // 登录名
        String session_key = jsonObject.getString("session_key");
        // 登录密码
        String iv = jsonObject.getString("iv");
        // unionid
        String encryptData = jsonObject.getString("encryptData");
        String decrypt = "";
        try {
            decrypt = GetPhoneNumber.decrypt(session_key, iv, encryptData);
        } catch (Exception e) {
            // TODO: handle exception
            resultObj.put("error_code", 1);
            resultObj.put("error_msg", "获取失败");
            resultObj.put("data", "");
            responseData(resultObj.toString(), resp);
            return;
        }
        JSONObject returnjsonObject = JSONObject.parseObject(decrypt);
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", returnjsonObject);
        responseData(resultObj.toString(), resp);
    }


    /**
     * 设置用户相关信息
     *
     * @param req
     * @param resp
     * @throws Exception 检查
     */
    @RequestMapping(value = "/setUserInfoByUserId")
    public void setUserInfoByUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JSONObject resultObj = new JSONObject();
        String str = getRequestBodyString(req);
        LogFactory.getLog(this.getClass()).info("setUserInfoByUserId-----------------------:" + str);
        if (StringUtil.isEmpty(str)) {
            responseErrorData("json error", resp);
            return;
        }
        // 就是头像，昵称，性别这些
        JSONObject jsonObject = JSONObject.parseObject(str);
        // USERID
        String userid = jsonObject.getString("userid");
        // 头像
        String avatarurl = jsonObject.getString("avatarurl");
        // 昵称
        String nickname = jsonObject.getString("nickname");
        nickname = nickname.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "");

        String city = jsonObject.getString("city");
        String province = jsonObject.getString("province");
        String country = jsonObject.getString("country");

        String birthday = jsonObject.getString("birthday");
        if (StringUtil.isEmpty(birthday)) {
            birthday = "";
        }
        // 性别 0男 1女
        String gender = jsonObject.getString("gender");
        apiService.updateUserInfoById(userid, avatarurl, nickname, city, province, country, gender, birthday);
        resultObj.put("error_code", 0);
        resultObj.put("error_msg", "获取成功");
        resultObj.put("data", userid);
        responseData(resultObj.toString(), resp);

    }


    /**
     * 从req中读取数据
     *
     * @param req
     * @return
     */
    private String getRequestBodyString(HttpServletRequest req) {
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }
        return builder.toString();
    }

    private void responseErrorData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        JSONObject resultObj = new JSONObject();
        resultObj.put("error_code", 1);
        resultObj.put("error_msg", string);
        responseData(resultObj.toString(), resp);
    }

    private void responseData(String string, HttpServletResponse resp) throws Exception {
        // TODO Auto-generated method stub
        responseDate("application/json;charset=UTF-8", string, resp);

    }

    private void responseDate(String contentType, String value, HttpServletResponse resp) throws Exception {
        resp.setContentType(contentType);
        resp.getWriter().write(value);
    }
}
